import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入login组件
import Login from '../components/Login.vue'
// 导入Home组件
import Home from '../components/Home.vue'
// 导入Welcome组件
import Welcome from '../components/Welcome.vue'
// 导入User组件
import User from '../components/users/User.vue'
// 导入Rights.Vue
import Rights from '../components/power/Rights.vue'
// 导入Roles组件
import Roles from '../components/power/Roles.vue'
// 导图Cate组件
import Cate from '../components/goods/Cate.vue'
// 导入Params组件
import Params from '../components/goods/Params.vue'
// 导如List
import GoodsList from '../components/goods/List.vue'
Vue.use(VueRouter)
// 导入Add
const routes = [
  // 新增路由规则
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      // 用户列表组件
      { path: '/users', component: User },
      // 权限列表组件
      { path: '/rights', component: Rights },
      // 用户列表组件
      { path: '/roles', component: Roles },
      // 商品分类组件
      { path: '/categories', component: Cate },
      // 分类参数组件
      { path: '/params', component: Params },
      // 商品列表组件
      { path: '/goods', component: GoodsList }
    ]
  }

]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
// to 将要访问哪个路径
// from 代表从哪来
// next 代表放行
router.beforeEach((to, from, next) => {
  // 如果访问的路径式/login，直接放行
  if (to.path === '/login') next()
  // 从sessionStorage中获取token的值
  const tokenStr = window.sessionStorage.getItem('token')
  // 判断tokenStr，如果有，代表登录了 ,如果没有，强制跳转会/login
  if (!tokenStr) return next('/login')
  next()
})

export default router
